package cn.iocoder.yudao.module.reading.controller.app.recording;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.reading.controller.app.recording.vo.RecordingCreateReqVO;
import cn.iocoder.yudao.module.reading.controller.app.recording.vo.RecordingRespVO;
import cn.iocoder.yudao.module.reading.controller.app.recording.vo.RecordingUploadReqVO;
import cn.iocoder.yudao.module.reading.controller.app.recording.vo.RecordingUploadRespVO;
import cn.iocoder.yudao.module.reading.service.recording.RecordingService;
import cn.iocoder.yudao.module.reading.service.file.ReadingFileService;
import cn.iocoder.yudao.module.reading.framework.util.StaticResourceUrlUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 用户 APP - 配音管理
 *
 * @author 芋道源码
 */
@Tag(name = "用户 APP - 配音管理")
@RestController
@RequestMapping("/reading/recordings")
@Validated
@Slf4j
public class RecordingController {

    @Resource
    private RecordingService recordingService;

    @Resource
    private ReadingFileService readingFileService;

    @Resource
    private StaticResourceUrlUtils staticResourceUrlUtils;

    @PostMapping("/upload")
    @Operation(summary = "上传录音文件")
    @PreAuthenticated
    public CommonResult<RecordingUploadRespVO> uploadRecording(
            @Parameter(description = "绘本ID", required = true) @RequestParam("bookId") Long bookId,
            @Parameter(description = "页面ID（可选）") @RequestParam(value = "pageId", required = false) Long pageId,
            @Parameter(description = "页码（可选，与pageId二选一）") @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
            @Parameter(description = "录音文件") @RequestParam("file") MultipartFile file,
            @Parameter(description = "录音时长（秒）") @RequestParam("duration") Integer duration,
            @Parameter(description = "录音质量", example = "medium") @RequestParam(value = "quality", required = false, defaultValue = "medium") String quality) {

        Long userId = getLoginUserId();

        log.info("📥 接收到录音上传请求 - bookId: {}, pageId: {}, pageNumber: {}, duration: {}, quality: {}, fileName: {}",
                bookId, pageId, pageNumber, duration, quality, file != null ? file.getOriginalFilename() : "null");

        // 处理 pageId 和 pageNumber 的转换
        Long actualPageId = pageId;
        if (actualPageId == null && pageNumber != null) {
            // 根据 bookId 和 pageNumber 查找 pageId
            actualPageId = recordingService.getPageIdByBookIdAndPageNumber(bookId, pageNumber);
            if (actualPageId == null) {
                return CommonResult.error(400, "找不到指定的绘本页面：bookId=" + bookId + ", pageNumber=" + pageNumber);
            }
        }

        if (actualPageId == null) {
            return CommonResult.error(400, "必须提供 pageId 或 pageNumber 参数");
        }

        log.info("上传用户录音，用户ID: {}, 绘本ID: {}, 页面ID: {}, 页码: {}, 文件名: {}, 时长: {}秒",
                userId, bookId, actualPageId, pageNumber, file.getOriginalFilename(), duration);

        try {
            // 构建上传请求
            RecordingUploadReqVO uploadReqVO = new RecordingUploadReqVO();
            uploadReqVO.setBookId(bookId);
            uploadReqVO.setPageId(actualPageId); // 使用转换后的 actualPageId
            uploadReqVO.setFile(file);
            uploadReqVO.setDuration(duration);
            uploadReqVO.setQuality(quality);

            log.info("构建上传请求完成，pageId: {}", uploadReqVO.getPageId());

            RecordingUploadRespVO result = recordingService.uploadRecording(userId, uploadReqVO);
            return success(result);
        } catch (Exception e) {
            log.error("上传录音失败", e);
            return CommonResult.error(500, "上传录音失败: " + e.getMessage());
        }
    }

    @PostMapping("/create")
    @Operation(summary = "创建配音记录")
    @PreAuthenticated
    public CommonResult<Long> createRecording(@Valid @RequestBody RecordingCreateReqVO createReqVO) {
        Long userId = getLoginUserId();
        Long recordingId = recordingService.createRecording(userId, createReqVO);
        return success(recordingId);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新配音记录")
    @PreAuthenticated
    public CommonResult<Boolean> updateRecording(
            @Parameter(description = "配音记录ID", required = true, example = "1") @PathVariable("id") Long id,
            @Valid @RequestBody RecordingCreateReqVO updateReqVO) {
        Long userId = getLoginUserId();
        recordingService.updateRecording(userId, id, updateReqVO);
        return success(true);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取配音记录详情")
    @PreAuthenticated
    public CommonResult<RecordingRespVO> getRecordingDetail(
            @Parameter(description = "配音记录ID", required = true, example = "1") @PathVariable("id") Long id) {
        Long userId = getLoginUserId();
        RecordingRespVO result = recordingService.getRecordingDetail(userId, id);
        return success(result);
    }

    @GetMapping("/my-list")
    @Operation(summary = "获取我的配音记录列表")
    @PreAuthenticated
    public CommonResult<List<RecordingRespVO>> getMyRecordings(
            @Parameter(description = "限制数量", example = "20") @RequestParam(value = "limit", required = false) Integer limit) {
        Long userId = getLoginUserId();
        List<RecordingRespVO> result = recordingService.getUserRecordings(userId, limit);
        return success(result);
    }

    @GetMapping("/book/{bookId}")
    @Operation(summary = "获取绘本的配音记录")
    @PreAuthenticated
    public CommonResult<List<RecordingRespVO>> getBookRecordings(
            @Parameter(description = "绘本ID", required = true, example = "1") @PathVariable("bookId") Long bookId) {
        Long userId = getLoginUserId();
        List<RecordingRespVO> result = recordingService.getBookRecordings(userId, bookId);
        return success(result);
    }

    @GetMapping("/page/{pageId}")
    @Operation(summary = "获取页面的配音记录")
    @PreAuthenticated
    public CommonResult<RecordingRespVO> getPageRecording(
            @Parameter(description = "页面ID", required = true, example = "1") @PathVariable("pageId") Long pageId) {
        Long userId = getLoginUserId();
        RecordingRespVO result = recordingService.getPageRecording(userId, pageId);
        return success(result);
    }

    @GetMapping("/list")
    @Operation(summary = "获取配音记录列表")
    public CommonResult<List<RecordingRespVO>> getRecordings(
            @Parameter(description = "绘本ID", example = "1") @RequestParam(value = "bookId", required = false) Long bookId,
            @Parameter(description = "限制数量", example = "10") @RequestParam(value = "limit", required = false) Integer limit) {
        List<RecordingRespVO> result = recordingService.getRecordings(bookId, limit);
        return success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除配音记录")
    @PreAuthenticated
    public CommonResult<Boolean> deleteRecording(
            @Parameter(description = "配音记录ID", required = true, example = "1") @PathVariable("id") Long id) {
        Long userId = getLoginUserId();
        recordingService.deleteRecording(userId, id);
        return success(true);
    }



    @GetMapping("/count")
    @Operation(summary = "统计配音数量")
    @PreAuthenticated
    public CommonResult<Long> countRecordings() {
        Long userId = getLoginUserId();
        Long count = recordingService.countUserRecordings(userId);
        return success(count);
    }

    @GetMapping("/check-existing")
    @Operation(summary = "检查页面是否已有录音")
    @PreAuthenticated
    public CommonResult<Boolean> checkExistingRecording(
            @Parameter(description = "绘本ID", required = true) @RequestParam("bookId") Long bookId,
            @Parameter(description = "页面ID（可选）") @RequestParam(value = "pageId", required = false) Long pageId,
            @Parameter(description = "页码（可选，与pageId二选一）") @RequestParam(value = "pageNumber", required = false) Integer pageNumber) {

        Long userId = getLoginUserId();
        // Long userId = 1L; // 使用测试用户ID

        // 处理 pageId 和 pageNumber 的转换
        Long actualPageId = pageId;
        if (actualPageId == null && pageNumber != null) {
            actualPageId = recordingService.getPageIdByBookIdAndPageNumber(bookId, pageNumber);
            if (actualPageId == null) {
                return CommonResult.error(400, "找不到指定的绘本页面：bookId=" + bookId + ", pageNumber=" + pageNumber);
            }
        }

        if (actualPageId == null) {
            return CommonResult.error(400, "必须提供 pageId 或 pageNumber 参数");
        }

        boolean hasExisting = recordingService.hasExistingRecording(userId, actualPageId);
        return success(hasExisting);
    }

}
